package com.quectel.cms.util;

import com.google.common.base.Preconditions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 快速从当前上下文拿到request和response对象
 *
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2023-08-30 09:22:00
 */
@Slf4j
public class MyRequestContextHolder {
    /**
     * 得到当前Request
     *
     * @return
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Preconditions.checkArgument(requestAttributes != null, "ServletRequestAttributes is null");
        HttpServletRequest httpServletRequest = requestAttributes.getRequest();
        Preconditions.checkArgument(httpServletRequest != null, "HttpServletRequest is null");
        return httpServletRequest;
    }


    /**
     * 得到当前Response
     *
     * @return
     */
    public static HttpServletResponse getCurrentResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Preconditions.checkArgument(requestAttributes != null, "ServletRequestAttributes is null");
        HttpServletResponse httpServletResponse = requestAttributes.getResponse();
        Preconditions.checkArgument(httpServletResponse != null, "HttpServletResponse is null");
        return httpServletResponse;
    }
}
